﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Quebec.Silverlight.Controls.TwitterControls
{
	public class TwitterReader : ItemsControl
	{
		private string _HashKey;
		public string HashKey 
		{
			get { return _HashKey; }
			set
			{
				_HashKey = value;
				LookupTwitsFromHashKey();
			}
		}

		public TwitterReader()
		{
			this.DefaultStyleKey = typeof(TwitterReader);
		}

		public override void OnApplyTemplate()
		{
			base.OnApplyTemplate();
		}

		private void LookupTwitsFromHashKey()
		{
			if (string.IsNullOrEmpty(HashKey))
				throw new ArgumentException("Searchkey is not valid");
			LookupTwits("#search?q=%23" + HashKey);
		}

		private void LookupTwits(string key)
		{
			if (string.IsNullOrEmpty(key))
				throw new ArgumentException("Key parameter is not valid");

			Uri twitterUri = new Uri("http://twitter.com/" + key);

			WebClient c = new WebClient();
			c.DownloadStringCompleted += new DownloadStringCompletedEventHandler(c_DownloadStringCompleted);
			c.DownloadStringAsync(twitterUri);
		}

		void c_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
		{
			if (e.Error == null)
			{
				this.ItemsSource = e.Result;
			}
			else
			{
				// TODO handle error
			}
		}
	}
}
